import { ref } from 'vue';
import * as Cesium from 'cesium';
import { Entity } from 'cesium';
import { getMarkerImage } from '@/utils/MapEntityImages';
import { v4 as uuidv4 } from 'uuid';
import mapPopSonComponents from '@/constants/components/mapPopSonComponents';
import { PopupVue } from '@/utils/cesium-popup/PopupVue';
import popUp from '@/components/popUp/index.vue';
import round from '@/assets/largescreen/yuan-jiazai.png';
import { useDialogStore } from '@/store/modules/useDialogStore';

interface IBillboard {
  image: string;
  color: Cesium.Color;
  rotation?: number;

  [key: string]: any;
}

export interface PointOptions {
  id?: string;
  name?: string;
  longitude: string;
  latitude: string;
  billboard?: IBillboard;

  [key: string]: any;
}

export const popup = {};
export const useCesiumPoints = () => {
  const points = ref<Entity[]>([]);
  const { flyTo } = useDialogStore();
  // 点位样式
  const defaultPointOptions: Partial<PointOptions> = {
    billboard: {
      // 图像地址，URI或Canvas的属性
      image: null,
      // 设置颜色和透明度
      color: Cesium.Color.WHITE.withAlpha(1),
      // 逆时针旋转
      rotation: 0,
      // 大小是否以米为单位
      sizeInMeters: false,
      // 相对于坐标的垂直位置
      verticalOrigin: Cesium.VerticalOrigin.CENTER,
      // 相对于坐标的水平位置
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
      pixelOffset: new Cesium.Cartesian2(0, 0),
      // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
      scale: 0.5,
      // 是否显示
      show: true
    }
  };

  /**
   * 添加一个点位
   * @param options 点位配置
   * @param name
   * @param title 用来点击点位时展示不同的组件
   * @returns 创建的实体
   */
  const addPoint = (options: PointOptions, name: string, title?: string) => {
    if (!window.viewer) {
      throw new Error('Cesium Viewer 未初始化...');
    }
    const image = getMarkerImage(name, options);

    if (image) {
      defaultPointOptions.billboard.image = image;
    } else {
      defaultPointOptions.billboard.image = null;
    }
    const mergedOptions = {
      ...options,
      name: options.name || options.alarmTitle,
      id: `Point_${uuidv4()}`,
      moduleId: title === '流量监测' ? options.code : options.id,
      ...defaultPointOptions,
      moduleTitle: title || name
    };

    const entity = window.viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(Number(mergedOptions.longitude), Number(mergedOptions.latitude)),
      name: mergedOptions.name || `Point_${Date.now()}`,
      description: JSON.stringify(mergedOptions) || '',
      billboard: mergedOptions.billboard,
      ...(mergedOptions.id ? { id: mergedOptions.id } : {})
    });
    points.value.push(entity);
    return entity;
  };

  /**
   * 清空当前点击模块所有点位
   */
  const clearAllPoints = (points: Entity[]): void => {
    points.forEach((point) => {
      window.viewer.entities.remove(point);
    });
  };
  //创建弹窗
  const createPopUp = (entity) => {
    try {
      const mapData = JSON.parse(entity.description.getValue());
      console.log(mapData.moduleTitle);
      if (mapData.moduleTitle !== '智能分析') {
        // 关闭所有已存在的弹窗
        Object.keys(popup).forEach((key) => {
          if (popup[key]) {
            popup[key].remove();
            delete popup[key];
          }
        });
        flyTo({ longitude: mapData.longitude, latitude: mapData.latitude }, 2000, getEntityById(mapData.moduleId));
      }
      if (mapPopSonComponents[mapData.moduleTitle]) {
        const popupKey = `${mapData.moduleTitle}_${mapData.id}_${Date.now()}`;
        const options = {
          component: popUp,
          position: entity.position.getValue(),
          props: {
            id: mapData.moduleId,
            mapData,
            componentChild: mapPopSonComponents[mapData.moduleTitle].component,
            type: mapPopSonComponents[mapData.moduleTitle].type,
            close: () => {
              if (popup[popupKey]) {
                popup[popupKey].remove();
                delete popup[popupKey];
              }
            }
          }
        };
        popup[popupKey] = new PopupVue(window.viewer, options);
      }
    } catch (e) {
      console.error('解析description失败:', e);
    }
  };
  /**
   * 根据ID获取点位
   * @param id 点位ID
   * @returns 点位实体或undefined
   */
  const getPointById = (id: string): Entity | undefined => {
    return points.value.find((point) => point.id === id);
  };
  //绘制管线
  const loadPipeline = (data, pipeLineType) => {
    const positions = parseGeometry(data.geometry);
    return window.viewer.entities.add({
      polyline: {
        positions: positions,
        width: 3,
        granularity: Cesium.Math.RADIANS_PER_DEGREE,
        material: getPipeLineColor(pipeLineType),
        arcType: Cesium.ArcType.NONE, //线的地理类型，NONE表示纯直线，GEODESIC表示为测地线，RHUMB表示等角航线，默认为测地线
        clampToGround: false, //是否贴地，默认为否
        shadows: Cesium.ShadowMode.DISABLED, //是否显示光照阴影，默认为否
        classificationType: Cesium.ClassificationType.BOTH
      }
    });
  };
  //返回颜色
  const getPipeLineColor = (pipeLineType: string): Cesium.Color => {
    return pipeLineType === '高压管线'
      ? Cesium.Color.fromCssColorString('#ff7070')
      : pipeLineType === '次高压管线'
        ? Cesium.Color.fromCssColorString('#fff780')
        : pipeLineType === '中压管线'
          ? Cesium.Color.fromCssColorString('#00ddff')
          : Cesium.Color.fromCssColorString('#30ffb3');
  };
  //解析几何信息
  const parseGeometry = (geometryStr) => {
    const coords = geometryStr.split(',');
    const positions = [];
    for (let i = 0; i < coords.length; i += 2) {
      const lon = parseFloat(coords[i]);
      const lat = parseFloat(coords[i + 1]);
      positions.push(Cesium.Cartesian3.fromDegrees(lon, lat));
    }
    return positions;
  };
  //根据moduleId 获取实体
  const getEntityById = (moduleId: string): Entity | undefined => {
    return window.viewer.entities.values.find((item) => {
      if (item.description) {
        const description = JSON.parse(item.description.getValue());
        return description.moduleId === moduleId;
      }
    });
  };
  //加载圆(预警范围)
  //加载圆
  const loadCircle = (data, distance) => {
    window.viewer.entities.removeById('circle');
    const circle = {
      id: 'circle',
      position: Cesium.Cartesian3.fromDegrees(Number(data.longitude), Number(data.latitude)),
      ellipse: {
        semiMinorAxis: distance,
        semiMajorAxis: distance,
        material: new Cesium.ImageMaterialProperty({
          image: round
        })
      }
    };
    window.viewer.entities.add(circle);
    flyTo({ longitude: Number(data.longitude), latitude: Number(data.latitude) }, distance * 5);
  };
  return {
    points,
    addPoint,
    loadPipeline,
    clearAllPoints,
    getPointById,
    createPopUp,
    loadCircle,
    getEntityById
  };
};
